package cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cart.mapper.CartMapper;
import cart.service.ICartService;
import cart.service.GoodsServiceFeignClient;
import cart.service.UserServiceFeignClient;
import common.dto.cartdto.CartDTO;
import common.dto.goodsdto.SkuDTO;
import common.dto.goodsdto.SpuVO;
import common.dto.userdto.UserCartDTO;
import common.model.cart.Cart;
import common.model.result.Result;
import common.model.result.ResultCodeEnum;
import common.model.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.Collections;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@Service
public class CartServerImpl implements ICartService {
    @Autowired
    private GoodsServiceFeignClient goodsServiceFeignClient;

    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserServiceFeignClient userServiceFeignClient;
    
    private static final String CART_LOCK_PREFIX = "cart:lock:";
    private static final long LOCK_TIMEOUT = 10; // 锁超时时间（秒）
    //添加购物车
    @Override
    public Result addToCart(Long uid, Long skuId, Integer number) {
        // 参数校验
        if (uid == null || skuId == null || number == null) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "参数不能为空");
        }
        if (number <= 0) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品数量必须大于0");
        }

        // 获取分布式锁
        String lockKey = CART_LOCK_PREFIX + uid + ":" + skuId;
        boolean locked = redisTemplate.opsForValue().setIfAbsent(lockKey, "1", LOCK_TIMEOUT, TimeUnit.SECONDS);
        if (!locked) {
            return Result.failure(ResultCodeEnum.SERVER_ERROR, "操作太频繁，请稍后重试");
        }

        try {
            // 检查购物车中是否已存在该商品
            Cart duplicateCart = cartMapper.selectOne(
                new LambdaQueryWrapper<Cart>()
                    .eq(Cart::getUserId, uid)
                    .eq(Cart::getSkuId, skuId)
            );
            if (duplicateCart != null) {
                return updateExistingCartItem(duplicateCart, number);
            }
            return addNewCartItem(uid, skuId, number);
        } finally {
            // 释放锁
            redisTemplate.delete(lockKey);
        }
    }
    //更新购物车商品的数量
    private Result updateExistingCartItem(Cart existingCart, Integer number) {
        // 获取最新的商品信息
        Result result = goodsServiceFeignClient.getGoodsDetail(existingCart.getSkuId());
        if (result.getCode() != 200) {
            return result;
        }

        String jsonObject = JSON.toJSONString(result.getData());
        SkuDTO skuGoodsDTO = JSONObject.parseObject(jsonObject, SkuDTO.class);
        
        // 检查商品状态
        if (!skuGoodsDTO.isStatus()) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品已下架");
        }
        
        // 检查库存
        int newNumber = number + existingCart.getQuantity();
        if (newNumber > skuGoodsDTO.getStock()) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品库存不足");
        }
        
        // 更新购物车数量和时间
        LocalDateTime now = LocalDateTime.now();
        cartMapper.update(null,
            new LambdaUpdateWrapper<Cart>()
                .eq(Cart::getId, existingCart.getId())
                .set(Cart::getQuantity, number + existingCart.getQuantity())
                .set(Cart::getUpdatedTime, now)
        );
        return Result.success(existingCart.getId());
    }
    //添加新购物车商品
    private Result addNewCartItem(Long uid, Long skuId, Integer number) {
        // 获取商品详情
        Result result = goodsServiceFeignClient.getGoodsDetail(skuId);
        if (result.getCode() != 200) {
            return result;
        }

        // 解析商品信息
        String jsonObject = JSON.toJSONString(result.getData());
        SkuDTO skuGoodsDTO = JSONObject.parseObject(jsonObject, SkuDTO.class);
        
        // 检查商品状态
        if (!skuGoodsDTO.isStatus()) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品已下架");
        }
        
        // 检查库存
        if (number > skuGoodsDTO.getStock()) {
            return Result.failure(ResultCodeEnum.BAD_REQUEST, "商品库存不足");
        }

        // 创建购物车记录
        LocalDateTime now = LocalDateTime.now();
        Cart cart = new Cart();
        cart.setSpuId(skuGoodsDTO.getSpuId());
        cart.setSkuId(skuId);
        cart.setQuantity(number);
        cart.setUserId(uid);
        cart.setSelected(true);
        cart.setPromotionId(0L);//TODO 活动id
        cart.setPromotionPrice(skuGoodsDTO.getPrice());
        cart.setStockSnapshot(skuGoodsDTO.getStock());
        cart.setIsDeleted(false);
        cart.setAddedTime(now);
        cart.setUpdatedTime(now);

        try {
            cartMapper.insert(cart);
            return Result.success(cart.getId());
        } catch (Exception e) {
            return Result.failure(ResultCodeEnum.INTERNAL_SERVER_ERROR, "添加购物车失败：" + e.getMessage());
        }
    }
    
    //删除购物车商品
    @Override
    public void deleteFromCart(String id) {
        cartMapper.deleteById(id);
    }
    
    //获取购物车列表
    @Override
    public Result getCartsByUid(Long uid) {
        List<Cart> cartList = cartMapper.selectList(
            new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, uid)
        );
        
        List<CartDTO> cartDTOList = new ArrayList<>();
        for (Cart cart : cartList) {
            CartDTO cartDTO = new CartDTO();
            // 使用BeanUtils复制相同字段名的属性
            BeanUtils.copyProperties(cart, cartDTO);
            
            // 获取SpuVo详情
            Result result = goodsServiceFeignClient.getSpuVo(cart.getSpuId());
            if (result.getCode() != 200) {
                return result;
            }
            // 获取SkuDTO详情
            Result skuResult = goodsServiceFeignClient.getSkuDTO(cart.getSkuId());
            if (skuResult.getCode() != 200) {
                return skuResult;
            }
            // 设置SpuVO
            cartDTO.setSpuVO(JSONObject.parseObject(JSON.toJSONString(result.getData()), SpuVO.class));
            // 设置SkuDTO
            cartDTO.setSkuDTO(JSONObject.parseObject(JSON.toJSONString(skuResult.getData()), SkuDTO.class));
            
            cartDTOList.add(cartDTO);
        }
        
        return Result.success(cartDTOList);
    }
    
    //根据id集合获取购物车列表
    @Override
    public Result getCartsByUidandCartIds(Long uid, List<String> cartIds) {
        List<Cart> cartList = new ArrayList<>();
        for (String cartId : cartIds) {
            Cart cart = cartMapper.selectOne(
                new LambdaQueryWrapper<Cart>()
                    .eq(Cart::getUserId, uid)
                    .eq(Cart::getId, cartId)
            );
            if (cart != null) {
                cartList.add(cart);
            }
        }
        return Result.success(cartList);
    }
    //根据id集合删除购物车
    @Override
    public void deleteCartByUidandCartIds(Long uid, List<String> cartIds) {
        cartMapper.delete(
            new LambdaQueryWrapper<Cart>()
                .eq(Cart::getUserId, uid)
                .in(Cart::getId, cartIds)
        );
    }
    
    //更新购物车数量
    @Override
    public void updateNumber(String id, Integer quantity) {
        cartMapper.update(null,
            new LambdaUpdateWrapper<Cart>()
                .eq(Cart::getId, id)
                .set(Cart::getQuantity, quantity)
        );
    }

    //后台
    //获取用户购物车列表
    @Override
    public Result getCartListByAdmin(Integer page, Integer size, String query) {
        // 创建返回结果列表
        List<UserCartDTO> userCartDTOList = new ArrayList<>();
        
        // 获取用户列表
        Result userResult = userServiceFeignClient.getUserListForCart();
        if (userResult.getCode() != 200) {
            return userResult;
        }
        
        List<User> users = JSON.parseArray(JSON.toJSONString(userResult.getData()), User.class);
        if (users == null || users.isEmpty()) {
            return Result.success(userCartDTOList);
        }
        
        // 根据query过滤用户
        if (query != null && !query.trim().isEmpty()) {
            users = users.stream()
                    .filter(user -> String.valueOf(user.getId()).contains(query) || 
                            (user.getNickName() != null && user.getNickName().contains(query)))
                    .collect(Collectors.toList());
        }
        
        // 为每个用户获取购物车信息
        for (User user : users) {
            UserCartDTO userCartDTO = new UserCartDTO();
            userCartDTO.setId(user.getId());
            userCartDTO.setUsername(user.getNickName());
            
            // 获取用户购物车列表
            List<Cart> userCarts = cartMapper.selectList(
                new LambdaQueryWrapper<Cart>()
                    .eq(Cart::getUserId, user.getId())
            );
            
            if (userCarts.isEmpty()) {
                continue; // 跳过没有购物车的用户
            }
            
            // 获取购物车中所有商品的ID
            List<Long> skuIds = userCarts.stream()
                    .map(Cart::getSkuId)
                    .collect(Collectors.toList());
            
            List<Long> spuIds = userCarts.stream()
                    .map(Cart::getSpuId)
                    .collect(Collectors.toList());
            
            // 批量获取SKU信息
            Map<Long, SkuDTO> skuMap = new HashMap<>();
            if (!skuIds.isEmpty()) {
                // 由于没有批量查询方法，逐个查询SKU信息
                for (Long skuId : skuIds) {
                    Result skuResult = goodsServiceFeignClient.getSkuDTO(skuId);
                    if (skuResult.getCode() == 200 && skuResult.getData() != null) {
                        SkuDTO skuDTO = JSON.parseObject(JSON.toJSONString(skuResult.getData()), SkuDTO.class);
                        skuMap.put(skuId, skuDTO);
                    }
                }
            }
            
            // 批量获取SPU信息
            Map<Long, SpuVO> spuMap = new HashMap<>();
            if (!spuIds.isEmpty()) {
                // 由于没有批量查询方法，逐个查询SPU信息
                for (Long spuId : spuIds) {
                    Result spuResult = goodsServiceFeignClient.getSpuVo(spuId);
                    if (spuResult.getCode() == 200 && spuResult.getData() != null) {
                        SpuVO spuVO = JSON.parseObject(JSON.toJSONString(spuResult.getData()), SpuVO.class);
                        spuMap.put(spuId, spuVO);
                    }
                }
            }
            
            // 根据query过滤购物车商品
            if (query != null && !query.trim().isEmpty()) {
                userCarts = userCarts.stream()
                        .filter(cart -> {
                            SpuVO spuVO = spuMap.get(cart.getSpuId());
                            if (spuVO != null) {
                                // 根据商品名称或类别过滤
                                return spuVO.getTitle() != null && spuVO.getTitle().contains(query) ||
                                       spuVO.getCategoryName() != null && spuVO.getCategoryName().contains(query);
                            }
                            return false;
                        })
                        .collect(Collectors.toList());
            }
            
            // 如果过滤后购物车为空，跳过此用户
            if (userCarts.isEmpty()) {
                continue;
            }
            
            // 转换为CartDTO列表
            List<CartDTO> cartDTOList = userCarts.stream()
                    .map(cart -> {
                        CartDTO cartDTO = new CartDTO();
                        cartDTO.setId(cart.getId());
                        cartDTO.setUserId(cart.getUserId());
                        cartDTO.setSpuId(cart.getSpuId());
                        cartDTO.setSkuId(cart.getSkuId());
                        cartDTO.setQuantity(cart.getQuantity());
                        cartDTO.setSelected(cart.getSelected());
                        cartDTO.setPromotionId(cart.getPromotionId());
                        cartDTO.setPromotionPrice(cart.getPromotionPrice());
                        cartDTO.setStockSnapshot(cart.getStockSnapshot());
                        cartDTO.setIsDeleted(cart.getIsDeleted());
                        
                        // 设置SKU信息
                        SkuDTO skuDTO = skuMap.get(cart.getSkuId());
                        if (skuDTO != null) {
                            cartDTO.setSkuDTO(skuDTO);
                        }
                        
                        // 设置SPU信息
                        SpuVO spuVO = spuMap.get(cart.getSpuId());
                        if (spuVO != null) {
                            cartDTO.setSpuVO(spuVO);
                        }
                        
                        return cartDTO;
                    })
                    .collect(Collectors.toList());
            
            userCartDTO.setCartListDTOs(cartDTOList);
            userCartDTOList.add(userCartDTO);
        }
        
        // 分页处理
        int total = userCartDTOList.size();
        int start = (page - 1) * size;
        int end = Math.min(start + size, total);
        
        if (start >= total) {
            // 创建带有总数的结果对象
            Result<List<UserCartDTO>> result = Result.success(Collections.emptyList());
            result.setData(Collections.emptyList());
            // 添加总数信息到消息中
            result.setMessage("Total: " + total);
            return result;
        }
        
        List<UserCartDTO> pagedResult = userCartDTOList.subList(start, end);
        
        // 创建带有总数的结果对象
        Result<List<UserCartDTO>> result = Result.success(pagedResult);
        // 添加总数信息到消息中
        result.setMessage("Total: " + total);
        return result;
    }

    //删除购物车项
    @Override
    public Result deleteCartItem(String id) {
        cartMapper.deleteById(id);
        return Result.success("成功删除购物车项");
    }

    //根据用户id集合删除所有购物车项
    @Override
    public Result deleteCartItemList(Long userId) {
        cartMapper.delete(new LambdaQueryWrapper<Cart>().eq(Cart::getUserId, userId));
        return Result.success("成功删除购物车项");
    }
}
